import csv


# 读取csv文件
def read_csv():
    with open("./file_dir/Test.csv", "r") as file:
        read = csv.reader(file)
        for row in read:
            print(row)


# 特殊分隔符的文件
def special_csv():
    with open('./file_dir/config.csv', 'r') as r:
        reader = csv.reader(r, delimiter="|")
        for row in reader:
            print(row)


# 字典的形式读取csv
def dict_csv():
    with open('./file_dir/Test.csv', 'r') as r:
        reader = csv.DictReader(r)
        for row in reader:
            print(row['user'], row['port'])


def write_csv():
    nums = [[123, 456, 789], [147, 258, 369]]
    # 如果已经存在，则不再写入
    with open('./file_dir/config_write.csv', 'w') as r:
        witered = csv.writer(r)
        for row in nums:
            witered.writerow(row)


def write_csv_from_dict():
    with open('./file_dir/config_dict.csv', 'w') as f:
        class_name = ['first', 'last']
        witered = csv.DictWriter(f, fieldnames=class_name)
        witered.writeheader()
        # 如果已经存在，则不再写入
        witered.writerow({"first": "Python", "last": "64"})
        witered.writerow({"first": "Java", "last": "128"})
        witered.writerow({"first": "PHP", "last": "32"})


if __name__ == '__main__':
    read_csv()
    special_csv()
    dict_csv()
    write_csv()
    write_csv_from_dict()
